import {Sequelize, Op} from 'sequelize';
import _ from 'lodash';

import BaseBusinessController from './../base/BaseBusinessController'

class RoleController extends BaseBusinessController {

    /**
     * 查询
     * @return {[type]} [description]
     */
    async actionFind() {
        super._validatePostId($_POST)
        let id = $_POST['id'];
        return await super._findRole(id);
    }


    /**
     * 查询
     * @return {[type]} [description]
     */
    async actionPermissions() {
        let id = $_POST['id'];
        let role = await this.modules('Role').where({ id }).first();
        if (!role) {
            throw new Error('角色不存在');
        }

        let sql = "select b.* from hz_role_permission rb INNER JOIN hz_permission b ON b.id = rb.permission_id WHERE rb.role_id = :role_id";
        return await db.sql(sql, {role_id: id})
    }


    /**
     * 修改
     * @return {[type]} [description]
     */
    async actionUpdatePermissions() {
        let id = $_POST['id'];
        let role = await this.modules('Role').where({ id }).first();
        if (!role) {
            throw new Error('角色不存在');
        }

        let permission_ids = $_POST['permission_ids'];

        await this.modules('Role.RolePermission').where({ role_id: id }).destroy();

        let result = []
        for(let permission_id of permission_ids){
            result.push({
                permission_id,
                role_id: id
            })
        }
        await this.modules('Role.RolePermission').bulkCreate(result);
        return true;
    }

    /**
     * 查询所有角色列表
     * @returns {Promise<*>}
     */
    async actionFindAll(){
        let {number, size} = this._getPage()
        let {app_id} = $_POST
        if(!app_id){
            throw new Error("缺少端参数");
        }
        console.log('state',this.state)
        let userRole=await super._findRoleByUser(this.state)
        console.log('userRole',userRole)
        let where={
            [Op.and]:[
                {
                    app_id:app_id
                },
                {
                    level: {
                    [Op.gte]: userRole.level
                  }
                }

            ]
        }
        console.log('where',where)

        return await this.modules('Role').where(where).order(['id', 'DESC']).page(number, size).select();
    }


    /**
     * 最大编号
     * @return {[type]} [description]
     */
    async actionNextNumber() {
        let {app_id} = $_POST
        if(!app_id){
            throw new Error("缺少端参数");
        }
        let result = await db.sql(`select max(number) as number from hz_role where app_id = ${app_id}`)
        if(result && result[0] && result[0].number){
            return result[0].number ++;
        }else{
            return 100000
        }
    }

    /**
     * 新增
     * @return {[type]} [description]
     */
    async actionAdd() {
       let {number, name, remark, app_id} = $_POST
        if(!number || !name || !app_id){
            throw new Error("参数缺失")
        }

        let existRole = await this.modules('Role').where({number, app_id}).first()
        if(existRole){
            throw new Error("该角色编号已存在")
        }

        let role = {number, name, remark, is_admin: 0, app_id}
        let data = await this.modules('Role').insert(role);
        if (data) {
            return data;
        } else {
            throw new Error('保存失败');
        }
    }

    /**
     * 编辑
     * @return {[type]} [description]
     */
    async actionUpdate() {
        let id = $_POST['id'];

        if(!id){
            throw new Error("ID参数缺失")
        }

        let data = await this.modules('Role').where({ id }).update($_POST);
        if (data) {
            return data;
        } else {
            throw new Error('保存失败');
        }
    }


    /**
     * 删除
     * @returns {Promise.<boolean>}
     */
    async actionDelete() {
        let id = $_POST['id'];

        if(!id){
            throw new Error("ID参数缺失")
        }

        let t = await db.transaction();
        try{
            await this.modules('Role').where({ id }).destroy({transaction: t});
            await this.modules('Role.RolePermission').where({role_id: id}).destroy({transaction: t});
            await this.modules('Account').where({role_id: id}).update({role_id: null},{transaction: t});
            await t.commit();
            return true;
        } catch (error) {
            await t.rollback();
            throw new Error("删除失败");
        }
    }


    _getPage(){
        let page = $_POST['page'];
        let number = page && page.number !== undefined ? page.number : 1;
        let size = page && page.size !== undefined ? page.size : 20;
        return {number, size}
    }
}

export default RoleController;